﻿using Dapper;
using InventoryIssue.API.Read.Application.Command.Stocktaking;
using InventoryIssue.Dtos;
using InventoryIssue.ErrorCode;
using InventoryIssue.Infrastructrue.Implement;
using MediatR;
using System.Text;

namespace InventoryIssue.API.Read.Application.Handler.Stocktaking
{
    public class GetStocktakingProductHandler : IRequestHandler<GetStocktakingProductCommand, APIResult<List<StocktakingProductDto>>>
    {
        private readonly DatabaseContext db;

        public GetStocktakingProductHandler(DatabaseContext db)
        {
            this.db = db;
        }
        public async Task<APIResult<List<StocktakingProductDto>>> Handle(GetStocktakingProductCommand request, CancellationToken cancellationToken)
        {
            APIResult<List<StocktakingProductDto>> result = new APIResult<List<StocktakingProductDto>>();
            StringBuilder sql = new StringBuilder();
			sql.Append(@"SELECT
						a.productId,
						a.productName,
						a.productCode,
						a.Specifications,
						b.LocationName,
						c.StocktakingId,
						c.Id,
						d.UnitName 
					FROM
						productmodel a
						JOIN locationmodel b ON a.LocationId = b.LocationId
						JOIN stocktakingproductmodel c ON a.ProductId = c.ProductId
						JOIN unitmodel d ON a.UnitId = d.UnitId 
					WHERE
						a.IsDel = 0 
						AND b.IsDel = 0 
						AND c.IsDel = 0 
						AND d.IsDel = 0
                        AND c.StocktakingId = @StocktakingId;"
            );
            var parameters = new
            {
                StocktakingId = request.StocktakingId
            };
            var data = await db.DapperConnection.QueryAsync<StocktakingProductDto>(sql.ToString(), parameters);
            result.Message = "显示成功";
            result.Code = APIEnum.Ok;
            result.Data = data.ToList();
            return result;
        }
    }
}
